package com.game.android;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.apache.log4j.chainsaw.Main;

import com.data.WDataConversion;
import com.game.serivce.GameRoomService;

/**
 * 机器人管理
 * @author wuxiaojian
 *
 */
public class AndroidManage {
	private Logger logger = Logger.getLogger(AndroidManage.class);
	private int androidCount = 0;
	private String[] androidName;
	protected boolean isChangeAndroidCount = false;
	public GameRoomService gameRoomService;
	public ArrayList<AndroidService> androidServices = new ArrayList<AndroidService>();
	public ArrayList<AndroidService> androidServices_Available = new ArrayList<AndroidService>();
	public ArrayList<AndroidService> androidServices_Useing = new ArrayList<AndroidService>();
	
	public AndroidManage(GameRoomService gameRoomService){
		this.gameRoomService = gameRoomService;
		init();
	}
	public void init(){
		try {
			androidName = readFile("androidNames").split(",");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
		
		androidServices.clear();
		androidServices_Available.clear();
		androidServices_Useing.clear();
		
		setAndroidCount();
		setTimerTask();
	}
	
	private String readFile(String fileName) throws UnsupportedEncodingException{
		String string = "";
		String path = Main.class.getClassLoader().getResource("").toString().substring(6);
		path = URLDecoder.decode("/" + path, "utf-8");
		File file = new File(path + fileName);
		try {
			FileInputStream fis = new FileInputStream(file);
			InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
			BufferedReader reader = new BufferedReader(isr);
			String tempstring = "";
			while ((tempstring = reader.readLine()) != null) {
				string = string + tempstring;
			}
			reader.close();
			isr.close();
			fis.close();
		} catch (FileNotFoundException e) {
			logger.error(e.getMessage(), e);
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		return string;
	}
	
	public void setAndroidCount(){
		isChangeAndroidCount = true;
		int count = gameRoomService.configRoomService.androidCount;
		
		int nowCount = 0;
		for (int i = 0; i < androidCount; i++) {
			if (!androidServices.get(i).getPlayerService().deskPlayer.isDelect()) {
				nowCount++;
			}
		}
		// 减少了机器人
		if (count < nowCount) {
			int c = nowCount - count;
			for (int i = androidServices.size() - 1; i >= 0; i--) {
				if (!androidServices.get(i).getPlayerService().deskPlayer.isDelect()) {
					c--;
					if (androidServices_Useing.contains(androidServices.get(i))) {
						androidServices.get(i).getPlayerService().deskPlayer.setDelect(true);

					} else if (androidServices_Available.contains(androidServices.get(i))) {
						androidServices_Available.remove(androidServices.get(i));
						androidServices.remove(i);
					} else {
						androidServices.remove(i);
					}
					if (c == 0) {
						break;
					}

				}
			}
		} else {
			// 增加了机器人
			AndroidService android;
			for (int i = nowCount; i < count; i++) {
				android = new AndroidService(i, this);
				android.getPlayerService().deskPlayer.setDelect(false);
				android.getPlayerService().deskPlayer.setGameNum(gameRoomService.configRoomService.gameNumberForDb);
				android.getPlayerService().deskPlayer.setRoomNum(gameRoomService.configRoomService.roomNumberForDb);
				androidServices.add(android);
				androidServices_Available.add(android);
			}
		}
		androidCount = count;
		isChangeAndroidCount = false;
	
	}
	private ScheduledExecutorService scheduExec = Executors.newSingleThreadScheduledExecutor();
	private void setTimerTask() {

		Runnable task = new Runnable() {
			public void run() {
				joinRoom();
				deal();
			}
		};
		
		scheduExec.scheduleWithFixedDelay(task, 0, 300, TimeUnit.MILLISECONDS);
	}
	private long addPlayerTime = 0;
	private void joinRoom() {
		if (addPlayerTime < System.currentTimeMillis()) {
			if (gameRoomService.configRoomService.androidJionTimeCha <0.0001f) {
				addPlayerTime = System.currentTimeMillis()
						+ WDataConversion.randLong(
								gameRoomService.configRoomService.androidJionTime[0],
								gameRoomService.configRoomService.androidJionTime[1]);

			} else {
				addPlayerTime = System.currentTimeMillis()
						+(long) (WDataConversion.randLong(
								gameRoomService.configRoomService.androidJionTime[0],
								gameRoomService.configRoomService.androidJionTime[1])
						* (androidServices_Useing.size() + 1) * gameRoomService.configRoomService.androidJionTimeCha);

			}
			
			if (androidServices_Available.size() > 0) {
				AndroidService androidService = androidServices_Available.get(0);
				androidServices_Available.remove(androidService);
				gameRoomService.joinRoom(androidService);
			}
		}
	}
	private void deal(){
		try {
			for (int i = 0; i < androidServices_Useing.size(); i++) {
				if (i < androidServices_Useing.size() && androidServices_Useing.get(i) != null) {
					androidServices_Useing.get(i).deal();
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	public String[] getAndroidName() {
		return androidName;
	}
	public void setAndroidName(String[] androidName) {
		this.androidName = androidName;
	}
	
}
